<template>
	<view class="user-info">
		<uv-form
			labelPosition="left"
			labelWidth="80px"
			errorType="toast"
			ref="form"
			:labelStyle="{ fontSize: '32rpx' }"
			:model="user"
			:rules="rules"
		>
			<uv-form-item label="头像" borderBottom>
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
					<image class="avatar" mode="aspectFill" :src="tempFilePath || userInfo.avatar"></image>
				</button>
			</uv-form-item>
			<uv-form-item label="昵称" prop="nickname" required borderBottom>
				<uv-input v-model="user.nickname" inputAlign="right" :placeholder="userInfo.nickname"></uv-input>
			</uv-form-item>
			<view class="confirm bottom" >
				<button class="button" @click="handleSubmitInfo">保存</button>
			</view>
		</uv-form>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import { getCredential } from '@/apis/cos.js';
import { uploadFile } from '@/utils/index.js';
import { updateUserInfo } from '@/apis/user/index.js';

export default {
	data() {
		return {
			tempFilePath: '', // 临时图片路径
			user: {
				avatar: '',
				nickname: ''
			},
			rules: {
				nickname: { required: true, trigger: 'blur', message: '昵称不能为空' }
			}
		};
	},
	computed: {
		...mapState(['userInfo'])
	},
	mounted() {
		const { id, nickname,avatar } = this.userInfo;
		this.user.id = id;
		this.user.avatar = avatar;
		if (nickname !== '微信用户') {
			this.user.nickname = nickname;
		}
	},
	methods: {
		// 更换头像
		handleChooseAvatar(e) {
			const { avatarUrl } = e.detail;
			this.tempFilePath = avatarUrl;
		},
		// 提交学生信息
		async handleSubmitInfo() {
			this.$refs['form']
				.validate()
				.then(async () => {
					let { tempFilePath, user } = this;

					// 如果头像更新了就上传到后端
					if (tempFilePath) {
						const suffix = tempFilePath.substr(tempFilePath.lastIndexOf('.') + 1);
						const opt = await getCredential(suffix, 'avatar');
						const avatar = await uploadFile(opt.data, tempFilePath);
						user.avatar = avatar;
					}

					// 更新学生信息
					const res = await updateUserInfo(user);
					if (res.code === 200) {
						this.$store.dispatch('fetchUserInfo');
						uni.navigateBack();
					}
				})
				.catch(error => {
					console.log(error);
				});
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: #fff;
}
.student-info .uv-form-item ::v-deep .uv-form-item__body {
	padding: 30rpx 0;
}
</style>

<style lang="scss" scoped>
.user-info {
	padding: 0 30rpx;
	border-top: 20rpx solid #eee;
	.uv-form-item:first-child {
		image {
			width: 90rpx;
			height: 90rpx;
			border-radius: 100%;
		}
		.avatar-wrapper {
			display: flex;
			justify-content: flex-end;
			margin: 0;
			padding-right: 0;
			background: none;
			&::after {
				border: none;
			}
		}
	}
}
</style>
